package utilities;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;

public class Pretreatment {

	/*
	 * setFilePath is to create the targetFolder for output no parameter
	 * handleType is 0 when no tempXX, and is 1 when tempXX
	 */
	public static void setFilePath(String targetFolder, int handleType) {

		try {
			File newFolder = new File(targetFolder);
			if (!newFolder.exists()) {
				newFolder.mkdir();
			} else {
				DelFolder(targetFolder, "");
			}

			if (handleType == 1) {
				BufferedWriter bw = new BufferedWriter(new FileWriter(new File(
						targetFolder + File.separator + "tempProfile")));
				bw.write("");
				bw.flush();
				bw.close();

				bw = new BufferedWriter(new FileWriter(new File(targetFolder
						+ File.separator + "tempImport")));
				bw.write("");
				bw.flush();
				bw.close();
			}
			System.out.println("Target file path has been setted!");
		} catch (IOException ex) {
			ex.printStackTrace();
		}
		return;
	}

	/*
	 * delete the files in delFolder but remain a folder named remainFolder
	 */
	public static void DelFolder(String delFolder, String remainFolder) {

		File file = new File(delFolder);
		if (!file.exists() || !file.isDirectory()) {
			return;
		}

		String[] tempFiles = file.list();
		File temp = null;
		for (int i = 0; i < tempFiles.length; i++) {
			if (tempFiles[i].equals(remainFolder))
				continue;
			if (delFolder.endsWith(File.separator)) {
				temp = new File(delFolder + tempFiles[i]);
			} else {
				temp = new File(delFolder + File.separator + tempFiles[i]);
			}
			if (temp.isFile()) {
				temp.delete();
			}
			if (temp.isDirectory()) {
				DelFolder(temp.getPath(), "");// 先递归删除文件夹里面的文件
				temp.delete();// 再删除空文件夹
			}
		}
	}
}
